<template>
  <!-- 列表 -->
  <ContentWrap class="full-height">
    <vxe-grid ref="gridRef" v-bind="gridOptions" v-on="gridEvents">
      <template #ie_sign="{ row }">
        <dict-tag :type="DICT_TYPE.IE_SIGN" :value="row.stsIefg" />
      </template>
      <template #ef_sign="{ row }">
        <dict-tag :type="DICT_TYPE.EF_SIGN" :value="row.stsEffg" />
      </template>
      <template #so_sign="{ row }">
        <dict-tag :type="DICT_TYPE.SO_SIGN" :value="row.stsShutocfg" />
      </template>
      <template #trans_sign="{ row }">
        <dict-tag :type="DICT_TYPE.TRANS_SIGN" :value="row.stsTranshpfg" />
      </template>
      <template #transit_sign="{ row }">
        <dict-tag :type="DICT_TYPE.TRANSIT_SIGN" :value="row.stsThrgcfg" />
      </template>
      <template #valid_sign="{ row }">
        <dict-tag :type="DICT_TYPE.VALID_SIGN" :value="row.stsIsvalid" />
      </template>
      <template #operate="{ row }">
        <el-button type="primary" size="small" @click="openForm('update', row.id)" v-hasPermi="['base:sts:update']" plain>编辑</el-button>
        <el-button type="danger" size="small" @click="handleDelete(row.id)" v-hasPermi="['base:sts:delete']" plain>删除</el-button>
      </template>
    </vxe-grid>
  </ContentWrap>

  <!-- 表单弹窗：添加/修改 -->
  <StsForm ref="formRef" @success="getList"/>

  <!-- 搜索抽屉 -->
  <SearchDrawer ref="searchRef" v-model="queryParams" @search="getList" />

</template>

<script setup lang="ts">
import { dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import { StsApi, StsVO } from '@/api/base/sts'
import StsForm from './StsForm.vue'
import type { VxeGridProps, VxeGridListeners,VxeGridInstance  } from 'vxe-table'
import SearchDrawer from './SearchDrawer.vue'
import {DICT_TYPE} from "@/utils/dict";

defineOptions({ name: 'Sts' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化

const queryParams = reactive({
    pageNo: 1,
  pageSize: 10,
  stsCdchange: undefined,
  stsIefg: undefined,
  stsEffg: undefined,
  stsShutocfg: undefined,
  stsTranshpfg: undefined,
  stsThrgcfg: undefined,
  stsName: undefined,
  stsIsvalid: undefined,
  stsRemark: undefined,
  createTime: [],
  deptId: undefined
})

const searchRef = ref()
// 表格实例
const gridRef = ref<VxeGridInstance>()

// 调用vxe grid query方法重载表格
const getList = () => {
  if (gridRef.value) {
    gridRef.value.commitProxy('query') // 触发表格重新加载数据
  }
}
// 获取表格数据
const fetchApi = () => {
  return new Promise(async (resolve) => {
    const res = await StsApi.getStsPage(queryParams)
    gridOptions.data = res.list
    resolve({
      page: {
        total: res.total
      },
      result: res.list
    })
  })
}

// 模拟后台接口
const delApi = (removeRecords: StsVO[]) => {
  return new Promise(async (resolve, reject) => {
    try{
      let ids = removeRecords.map((item) => item.id).join(',')
      await StsApi.deleteStss(ids)
      setTimeout(() => {
        resolve({
          result: [],
          msg: `delete，${removeRecords.length}条`
        })
      }, 100)
    }catch (e) {
      reject(e)
    }
  })
}

const gridOptions = reactive<VxeGridProps<StsVO>>({
  stripe: true,
  border: true,
  keepSource: true,
  height: '100%',
  printConfig: {},
  importConfig: {},
  exportConfig: {},
  columnConfig: {
    resizable: true
  },
  pagerConfig: {
    enabled: true,
    pageSize: 10
  },
  editConfig: {
    trigger: 'click',
    mode: 'row',
    showStatus: true
  },
  toolbarConfig: {
    import: true,
    export: true,
    print: true,
    zoom: true,
    custom: true,
    // slots: {
    //   buttons: 'toolbar_buttons'
    // },
    tools: [
      { name: '新增', code: 'add', status: 'primary' },
      { name: '删除', code: 'del', status: 'error' },
      { name: '', code: 'search', icon: 'vxe-icon-search', status: 'info' }
    ]
  },
  proxyConfig: {
    props: {
      result: 'result',
      total: 'page.total'
    },
    ajax: {
      // 接收 Promise
      query: ({ page }) => {
        queryParams.pageNo = page.currentPage
        queryParams.pageSize = page.pageSize
        return fetchApi()
      },
      // body 对象： { removeRecords }
      delete: ({ body }) => {
        return delApi(body.removeRecords)
      }
    }
  },
  columns: [
    { type: 'checkbox', width: 50 },
    { type: 'seq', width: 70 },
    { field: 'stsCdchange', title: '箱状态', minWidth: '100px' },
    { field: 'stsIefg', title: '进出口标识', minWidth: '100px', slots: { default: 'ie_sign' } },
    { field: 'stsEffg', title: '空重标识', minWidth: '100px', slots: { default: 'ef_sign' } },
    { field: 'stsShutocfg', title: '退关标识', minWidth: '100px', slots: { default: 'so_sign' } },
    { field: 'stsTranshpfg', title: '中转标识', minWidth: '100px', slots: { default: 'trans_sign' } },
    { field: 'stsThrgcfg', title: '过境标识', minWidth: '100px', slots: { default: 'transit_sign' } },
    { field: 'stsName', title: '状态名称', minWidth: '100px' },
    { field: 'stsIsvalid', title: '有效标识', minWidth: '100px', slots: { default: 'valid_sign' } },
    { field: 'createTime', title: '创建时间', minWidth: '100px', formatter: dateFormatter },
    { title: '操作', width: 200, slots: { default: 'operate' } }
  ],
  data: []
})

const gridEvents: VxeGridListeners = {
  toolbarButtonClick(params) {
    console.log(params.code)
  },

  toolbarToolClick({ code }) {
    // console.log(123, code, tool)
    switch (code) {
      case 'search':
        handelSearch()
        break
      case 'add':
        openForm('create')
        break
      case 'del':
        if (gridRef.value) {
          gridRef.value.commitProxy('delete')
        }
        break
    }
  }
}

const handelSearch = () => {
  searchRef.value?.open()
}

/** 添加/修改操作 */
const formRef = ref()
const openForm = (type: string, id?: number) => {
  formRef.value.open(type, id)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await StsApi.deleteSts(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 导出按钮操作 */
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    const data = await StsApi.exportSts(queryParams)
    download.excel(data, '箱状态.xls')
  } catch {
  } finally {
  }
}
</script>
